import router from '@/router'
import store from '@/vuex'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'


const whiteList = ['/login']

// 路由拦截器
router.beforeEach(async (to, from, next) => {

    //判断是否已有Token存在
    if(getToken()){
        if(to.path === '/login'){
            next({ path: '/' })
        }else{
                try{
                    await store.dispatch('user/getInfo')
                    // await store.dispatch('user/getMenuList')
                    next()
                }catch(error){
                    await store.dispatch('user/resetToken')
                    Message.error(error || 'getUserInfo Error')
                    // next(`/login?redirect=${to.path}`)
                    next({path: '/'})
                }
        }
    }else{
        // 没有Token

        if (whiteList.indexOf(to.path) !== -1 || to.path === '/login') {
            next();
        } else {
            // 如果当前路径不是登录页，则重定向到登录页，并可携带原始路径作为参数
            next({ path: '/login', query: { redirect: to.path } });
        }
    }


})



